package com.nsoft.html5npub;

import com.nsoft.html5npub.business.BookLoader;
import com.nsoft.html5npub.objects.BookItem;
import com.nsoft.html5npub.objects.Settings;
import com.nsoft.html5npub.objects.ViewEngineListener;
import com.nsoft.html5npub.objects.Settings.InterfaceType;
import com.nsoft.html5npub.R;
import com.nsoft.html5npub.utils.BookPreviewPanel;
import com.nsoft.html5npub.utils.BookmarkViewPanel;
import com.nsoft.html5npub.utils.Constant;
import com.nsoft.html5npub.utils.ChapterViewPanel;
import com.nsoft.html5npub.utils.SimpleGestureFilter;
import com.nsoft.html5npub.utils.SimpleGestureFilter.SimpleGestureListener;
import com.nsoft.html5npub.utils.engine;
import com.nsoft.html5npub.utils.utils;
import com.nsoft.html5npub.utils.viewengine;

import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ViewFlipper;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;

public class ViewActivity extends Activity 
			implements SimpleGestureListener,
						ViewEngineListener {
	
    Animation animFlipInForeward;
    Animation animFlipOutForeward;
    Animation animFlipInBackward;
    Animation animFlipOutBackward;
	
	private SimpleGestureFilter detector;
	private ViewFlipper pages;
	
	BookPreviewPanel bookPreviewPanel=null;
	ChapterViewPanel previewPanel=null;
	BookmarkViewPanel bookmarkPanel=null;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.
        				LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.
                		FLAG_FULLSCREEN);
        
        if (Settings.getInterfaceType()==
        			InterfaceType.VerticalList){
        	setContentView(R.layout.book_detail_view);
        }else{
        	setContentView(R.layout.book_detail_view_grid);
        }
        detector = new SimpleGestureFilter(this,this);
        
        animFlipInForeward = AnimationUtils.
        		loadAnimation(this,R.anim.flipin);
        animFlipOutForeward = AnimationUtils.
        		loadAnimation(this,R.anim.flipout);
        animFlipInBackward = AnimationUtils.
        		loadAnimation(this,R.anim.flipin_reverse);
        animFlipOutBackward = AnimationUtils.
        		loadAnimation(this,R.anim.flipout_reverse);

        
        pages=(ViewFlipper)findViewById(R.id.mainViewFlipper);
        pages.setBackgroundColor(Color.BLACK);
        pages.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(
					View v, MotionEvent event) {
				detector.onTouchEvent(event);
				return true;
			}
		});

        placeViewParent();
        
        startButton();
        startUp();
    }
    
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
    	super.onConfigurationChanged(newConfig);
    	
    	placeViewParent();
    }
    
    private void placeViewParent(){
    	int devWidth=utils.getRealMetrics(this).widthPixels;
    	int devHeight=utils.getRealMetrics(this).heightPixels;
    	int newFitHeight=(int)((float)devWidth/
    					Constant.pagesize.RATE);
    	
    	RelativeLayout.LayoutParams lp;
    	
    	if (newFitHeight<=devHeight){
    		lp=new RelativeLayout.LayoutParams(
    				RelativeLayout.LayoutParams.MATCH_PARENT,
    				newFitHeight);
    		lp.addRule(RelativeLayout.CENTER_VERTICAL);
    		pages.setLayoutParams(lp);
    	}else{
    		lp=new RelativeLayout.LayoutParams(
    				RelativeLayout.LayoutParams.MATCH_PARENT,
					RelativeLayout.LayoutParams.MATCH_PARENT);
    		lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
    		pages.setLayoutParams(lp);
    	}
    	
    }
    
    private void startButton(){
    	final LinearLayout layoutPopup=
    			(LinearLayout)findViewById(
    						R.id.layoutPopupView);
    	
    	RelativeLayout toolbarBookView=
    			(RelativeLayout)findViewById(
    						R.id.toolbarBookView);
    	toolbarBookView.setVisibility(View.GONE);
    	
    	ImageButton homeBtn=(ImageButton)
        		findViewById(R.id.homeButton);
        homeBtn.setOnClickListener(new View.
        		OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent=new Intent();
				setResult(RESULT_OK,intent);
				releaseResources();
				finish();
			}
		});
        
        ImageButton bookPreviewBtn=(ImageButton)
        		findViewById(R.id.bookpreviewButton);
        bookPreviewBtn.setOnClickListener(
        		new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (bookPreviewPanel==null){
					hideAllPopups();
					
					bookPreviewPanel=new BookPreviewPanel(
							ViewActivity.this,layoutPopup);
					bookPreviewPanel.show();
				}else{
					bookPreviewPanel.hide();
					bookPreviewPanel=null;
				}
			}
		});
        
        ImageButton bookmarkListBtn=(ImageButton)
    			findViewById(R.id.bookmarkListButton);
        bookmarkListBtn.setOnClickListener(
        		new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (bookmarkPanel==null){
					hideAllPopups();
					
					bookmarkPanel=new BookmarkViewPanel(
		    			ViewActivity.this,layoutPopup);
					bookmarkPanel.show();
		    	}else{
		    		bookmarkPanel.hide();
		    		bookmarkPanel=null;
		    	}
			}
		});
        
        ImageButton bookmarkBtn=(ImageButton)
        		findViewById(R.id.bookmarkButton);
        bookmarkBtn.setOnClickListener(new View.
        		OnClickListener() {
			
			@Override
			public void onClick(View v) {
				addBookmark();
			}
		});
        
    }

    private void startUp(){
    	Intent intent=getIntent();
    	int pos=intent.getExtras().getInt(
    		Constant.booklist.BOOK_INDEX_TRANSFER);
    	BookItem book=engine.getBookItem(pos);
    	
    	new BookLoader(this,this.pages,book).execute();
    	
    	viewengine.setViewEngineListener(this);
    	/*
    	bookPath=utils.getBookPath()+Constant.PATH_SPLITTER+
    			book.getContentName();
    	
    	String bookConfigPath=bookPath+Constant.PATH_SPLITTER+
    			Constant.xml.XML_BOOK_CONFIG_FILE;
    	
    	pages.removeAllViews();
    	viewengine.getBookFromBookConfig(bookConfigPath);
    	
    	View[] viewList=viewengine.createViews(this);
    	for (int i=0;i<viewList.length;i++){
    		pages.addView(viewList[i]);
    	}
    	*/
    }
    
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
    	this.detector.onTouchEvent(ev);
    	return super.dispatchTouchEvent(ev);
    }
    
    @Override
    public void onSwipe(int direction) {

    	switch (direction) {
    		case SimpleGestureFilter.SWIPE_RIGHT : {
    	    	pages.setInAnimation(animFlipInBackward);
    			pages.setOutAnimation(animFlipOutBackward);
    			pages.showPrevious();
    	        break;
    		}
    		case SimpleGestureFilter.SWIPE_LEFT : {
    	    	pages.setInAnimation(animFlipInForeward);
    			pages.setOutAnimation(animFlipOutForeward);
    			pages.showNext();
    	        break;
    		}
    		case SimpleGestureFilter.SWIPE_DOWN : {
    	        break;
    		}
    		case SimpleGestureFilter.SWIPE_UP : {
    			break;
    		}
    	}
    }
    
    @Override
    public void onDoubleTap() {
    	RelativeLayout toolbarBookView=(RelativeLayout)
				this.findViewById(R.id.toolbarBookView);
    	toolbarBookView.setVisibility(
				toolbarBookView.getVisibility()==View.GONE?
						View.VISIBLE:View.GONE);
    	
    	hideAllPopups();

		openChapterList(toolbarBookView.getVisibility()==
											View.VISIBLE);
    }
    
    @Override
    public void eventFired(EventData e) {
    	this.pages.setDisplayedChild(e.pageIndexX);
    	/**
    	bookmarkPanel=null;
    	*/
    	hideAllPopups();
    }
    
    @Override
    public void onBackPressed() {
    	AlertDialog.Builder alert=
				new AlertDialog.Builder(this);
			alert.setIcon(R.drawable.ic_help);
			alert.setTitle(Constant.DIALOG_CONFIRM).
				setMessage(Constant.booklist.
							BLF_QUIT_BOOKVIEW).
				setPositiveButton(Constant.DIALOG_YES,
					new DialogInterface.OnClickListener(){
						@Override
						public void onClick(
								DialogInterface arg0, 
								int arg1){
							releaseResources();
							finish();
						}
				}).setNegativeButton(Constant.DIALOG_NO,
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(
								DialogInterface dialog,
								int which){
							dialog.cancel();
						}
				}).create().show();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater inflater=getMenuInflater();
        inflater.inflate(R.menu.view_option_menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch(item.getItemId()){
	    	case R.id.itemAddBookmark:{
	    		addBookmark();
	    		break;
	    	}
	    	case R.id.itemOpenChapterList:{
	    		openChapterList(true);
	    		break;
	    	}
    	}
    	
    	return super.onOptionsItemSelected(item);
    }
    
    private void addBookmark(){
    	View view=pages.getCurrentView();
		int viewIndex=pages.getDisplayedChild();
		String pageId=(String)view.getTag();
		
		if (viewengine.isBookmarkExist(pageId))
			return;
		viewengine.addBookmark(pageId,viewIndex,0);
		addBookmarkToView(viewIndex);
    }
    
    private void openChapterList(boolean isToolbarExist){
    	if (!isToolbarExist)
    		return;
    	
    	if (previewPanel==null){
    		hideAllPopups();
    		
    		previewPanel=new ChapterViewPanel(this,
    					(ViewGroup)this.pages.getParent());
    		previewPanel.show();
    	}else{
    		previewPanel.hide();
    		previewPanel=null;
    	}
    }
    
    /**
     * remove all popup windows and navigator
     */
    private void hideAllPopups(){
    	/**
    	 * 1. close chapter list
    	 */
    	if (previewPanel!=null){
    		previewPanel.hide();
    		previewPanel=null;
    	}
    	
    	/**
    	 * 2. close bookmark list
    	 */
    	if (bookmarkPanel!=null){
    		bookmarkPanel.hide();
    		bookmarkPanel=null;
    	}
    	
    	/**
    	 * 3. close page list
    	 */
    	if (bookPreviewPanel!=null){
    		bookPreviewPanel.hide();
			bookPreviewPanel=null;
    	}
    	
    	System.gc();
    }
    
    private void releaseResources(){
    	try{
    		this.pages.removeAllViews();
    		this.pages=null;
    		viewengine.removeBeforeQuit();
    		System.gc();
    	}catch(Exception e){
    		Log.e("ViewActivity.releaseResources()",
    			e.getClass()+": "+e.getMessage());
    	}
    	if (previewPanel!=null){
    		previewPanel.hide();
    		previewPanel=null;
    	}
    }
    
    private void addBookmarkToView(int viewIdx){
    	View currentView=pages.getChildAt(viewIdx);
    	ImageButton bookmarkIconBtn=(ImageButton)currentView.
				findViewById(R.id.bookmarkIconButton);
    	bookmarkIconBtn.setVisibility(View.VISIBLE);
    }
}
